package com.tangsm.spring.boot.aliyun.bailian.service;

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.audio.ttsv2.enrollment.Voice;
import com.alibaba.dashscope.audio.ttsv2.enrollment.VoiceEnrollmentService;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.tangsm.spring.boot.aliyun.bailian.dto.CreatVoiceDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;

@Slf4j
@Service
public class VoiceServiceImpl implements VoiceService {
    /**
     * 克隆音色对应的语音识别模型版本
     */
    private static final String TARGET_MODEL = "cosyvoice-v2";

    /**
     * 阿里云百炼大模型API密钥
     */
    @Value("${alibaba.api-key}")
    private String apiKey;

    /**
     * 创建音色
     *
     * @param creatVoiceDto 创建音色参数
     * @return 音色ID
     */
    @Override
    public String createVoice(CreatVoiceDto creatVoiceDto) {
        try {
            VoiceEnrollmentService service = new VoiceEnrollmentService(apiKey);
            Voice voice = service.createVoice(TARGET_MODEL, creatVoiceDto.getVoiceName(), creatVoiceDto.getFileUrl());
            return voice.getVoiceId();
        } catch (NoApiKeyException e) {
            log.error("创建音色异常，Api Key有误", e);
        } catch (InputRequiredException e) {
            log.error("创建音色异常，原因：{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 删除音色
     *
     * @param voiceId 音色ID
     * @return 成功失败
     */
    @Override
    public boolean deleteVoice(String voiceId) {
        try {
            VoiceEnrollmentService service = new VoiceEnrollmentService(apiKey);
            service.deleteVoice(voiceId);
            return true;
        } catch (NoApiKeyException e) {
            log.error("删除音色异常，Api Key有误", e);
        } catch (InputRequiredException e) {
            log.error("删除音色异常，原因：{}", e.getMessage(), e);
        }
        return false;
    }

    /**
     * 使用音色，语音合成
     *
     * @param voiceId 音色ID
     * @param text    合成文本
     * @return 音频数据
     */
    @Override
    public byte[] useVoice(String voiceId, String text) {
        try {
            // 使用复刻的声音来合成文本为语音
            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                    .apiKey(apiKey)
                    .model(TARGET_MODEL)
                    .voice(voiceId)
                    .build();

            SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
            ByteBuffer audio = synthesizer.call(text);

            // 将ByteBuffer转换为byte数组返回
            byte[] bytes = new byte[audio.remaining()];
            audio.get(bytes);
            return bytes;
        } catch (Exception e) {
            throw new RuntimeException("语音合成失败", e);
        }
    }
}
